package io.xxx.xbutler.service;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hy.corecode.idgen.WFGIdGenerator;
import io.xxx.xbutler.data.ExportTaskMapper;
import io.xxx.xbutler.domain.ExportTask;
import io.xxx.xbutler.domain.ExportTaskType;
import io.xxx.xbutler.domain.User;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

@Slf4j
@Service
public class ExportTaskService {

    @Resource
    private WFGIdGenerator idGenerator;

    @Resource
    private ExportTaskMapper exportTaskMapper;

    public Page<ExportTask> list(ExportTask exportTask, Integer pageNumber, Integer pageSize) {
        LambdaQueryWrapper<ExportTask> wrapper = new LambdaQueryWrapper<ExportTask>()
                .orderByDesc(ExportTask::getCreatedTime);
        if (StringUtils.hasText(exportTask.getName())) {
            wrapper.like(ExportTask::getName, exportTask.getName());
        }
        if (StringUtils.hasText(exportTask.getCreatedName())) {
            wrapper.like(ExportTask::getCreatedName, exportTask.getCreatedName());
        }

        return exportTaskMapper.selectPage(new Page<>(pageNumber, pageSize), wrapper);
    }

    /**
     * 创建导出任务。
     *
     * @param type 任务类型
     * @param params 参数
     * @param user 用户信息
     * @return 任务ID
     */
    public long create(ExportTaskType type, Object params, User user) {
        LocalDateTime now = LocalDateTime.now();
        long id = idGenerator.next();
        ExportTask exportTask = new ExportTask()
                .setType(type)
                .setParams(JSON.parseObject(JSON.toJSONString(params)))
                .setCreatedId(user.getId())
                .setCreatedName(user.getName())
                .setCreatedTime(now)
                .setUpdatedId(user.getId())
                .setUpdatedName(user.getName())
                .setUpdatedTime(now);
        exportTaskMapper.insert(exportTask);
        return id;
    }
}
